<template>
  <div class="segment">
    <a-button
      v-for="(item, index) in list"
      :key="item"
      :class="['segment-item', index === selectedIndex ? 'segment-item__selected' : '']"
      @click="(e) => handleClick(e, item, index)"
    >
      {{ item }}
    </a-button>
  </div>
</template>

<script lang="ts">
  import { defineComponent, reactive, toRefs } from 'vue'
  import { Button } from 'ant-design-vue'

  export default defineComponent({
    name: 'Segment',
    components: { [Button.name]: Button },
    props: {
      list: {
        type: Array,
        default: () => []
      }
    },
    emits: ['click'],
    setup(props, { emit }) {
      const state = reactive({
        selectedIndex: undefined
      })

      const handleClick = (e, item, index) => {
        if (index === state.selectedIndex) {
          state.selectedIndex = undefined
          item = ''
        } else {
          state.selectedIndex = index
        }
        emit('click', item)
      }

      return {
        ...toRefs(state),
        handleClick
      }
    }
  })
</script>

<style lang="scss" scoped>
  $themeColor: #f50;

  .segment {
    border: 1px solid $themeColor;
    border-radius: 5px;

    .segment-item {
      color: $themeColor;
      border: 0 solid #fff;
      border-right: 1px solid $themeColor;
      border-radius: 0;

      &:last-child {
        border-right: 0 solid #fff;
        border-radius: 0 5px 5px 0;
      }

      &:first-child {
        border-radius: 5px 0 0 5px;
      }
    }

    .segment-item__selected {
      color: #fff;
      background-color: $themeColor;
    }
  }
</style>
